package com.zhxxfwzx.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zhxxfwzx.common.lang.Const;
import com.zhxxfwzx.common.lang.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Description TODO
 * @title: AuthController
 * @Author LiJing
 * @Date: 2021/6/158:11 下午
 * @Version 1.0
 */
@Slf4j
@RestController
public class AuthController extends BaseController{
    @Autowired
    DefaultKaptcha defaultKaptcha;
    @GetMapping("/captcha")
    public RespBean kaptcha(HttpServletResponse resp) throws IOException {
        String key = UUID.randomUUID().toString();
        String code = defaultKaptcha.createText();

        BufferedImage image = defaultKaptcha.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        Base64Encoder encoder = new Base64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + Base64Encoder.encode(outputStream.toByteArray());
        redisUtil.hset(Const.CAPTCHA_KEY, key, code,120);

        log.info("验证码：{}---{}",key, code);

        resp.setHeader("Cache-Control", "no-state");
        resp.setHeader("Param", "no-cache");
        resp.setDateHeader("Expires", 0);
//        resp.setContentType("image/jpeg");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        return RespBean.ok("操作成功",
                MapUtil.builder()
                        .put("token", key)
                        .put("kaptchaImg", base64Img)
                        .build()
        );
    }

}
